package cm

import (
	"gitee.com/law-api/log"
	apiTypes "gitee.com/law-api/types"

	"github.com/PicoChain/common"
)

//GetFileStatus find what the transaction filled in the past time.
func (cm *ClientManager) GetProofData(index string, mode int, txhash string, num uint64) (*apiTypes.ProofData, error) {
	//choose a random client to read status
	_, c := cm.randomClient()

	//read txs places
	tx, err := cm.getTransactionByHash(c, common.HexToHash(txhash))
	if err != nil || tx == nil {
		log.Warn("GetFileStatus-lookuptx", "invaild txhash", txhash, "err", err)
		return nil, err
	}

	//read contracter
	contracter, err := cm.findContract(num)
	if err != nil {
		log.Warn("GetFileStatus-lookupContract", "err", err)
		return nil, ErrCtrCall
	}

	//read proof data from contracter
	fs, err := contracter.getProofData(index, mode, tx)
	if err != nil {
		log.Warn("GetFileStatus-readstatus", "addr", contracter.contractAddr(), "err", err)
		return nil, ErrCtrCall
	}

	//contract messgae to proof data
	proof := apiTypes.NewProofData(fs.FileId, fs.FileHash, fs.FileSm3, fs.FileMd5, fs.TimeStamp)

	return proof, err
}

//GetChainStatus find where the transaction storage
func (cm *ClientManager) GetChainStatus(txhash string) (*apiTypes.ChainStatus, error) {
	//choose a random client to read status
	_, c := cm.randomClient()

	//read txs places
	tx, err := cm.getTransactionByHash(c, common.HexToHash(txhash))
	if err != nil || tx == nil {
		log.Warn("GetChainStatus-lookup-tx", "invaild txhash", txhash, "err", err)
		return nil, ErrTxPending
	}
	block, err := cm.getBlockByTxHash(c, common.HexToHash(txhash))
	if err != nil {
		log.Warn("GetChainStatus-lookup-block", "invaild txhash", txhash, "err", err)
		return nil, ErrTxPending
	}
	status := apiTypes.NewChainStatus(block.NumberU64(), block.Hash(), tx.Hash(), block.Time().Uint64())

	return status, nil
}
